package com.hs.conc.thread;

/**
 * @Author: songhao
 * @Date: 2021/8/28
 * @Description:
 * 主线程获取子线程的值
 * 方法：通过wait/notify方式实现
 */
public class MyThread3 extends Thread{

    public static void main(String[] args) throws Exception{

        long start=System.currentTimeMillis();

        //创建一个线程，并进行阻塞
        MyThread3 myThread = new MyThread3();
        myThread.start();

        int result = myThread.getSum();

        // 确保  拿到result 并输出
        System.out.println("计算结果为：" + result);
        System.out.println("使用时间："+ (System.currentTimeMillis()-start) + " ms");
    }

    public int getSum() throws Exception{
        synchronized(this){
            if(GlobalValue.result == 0){
                //表示未赋值，就阻塞住
                wait();
            }
        }
        return GlobalValue.result;
    }

    @Override
    public void run() {
        synchronized(this){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            GlobalValue.result = sum();
            //唤醒上面的线程
            notifyAll();
        }
    }

    private static int sum() {
        return fibo(36);
    }

    private static int fibo(int a) {
        if ( a < 2)
            return 1;
        return fibo(a-1) + fibo(a-2);
    }
}
